"use client"; // Keep this for the client component logic

import React, { Suspense } from "react"; // Import Suspense
import { useSearchParams } from 'next/navigation';
import { usePlan } from "../hooks/usePlan";
import LoadingOverlay from "../components/LoadingOverlay";
import PlanSelectionInterface from "../components/PlanSelectionInterface";
import MainInterface from "../components/MainInterface";

// Define the client component containing the original logic
function ChooseClientContent() {
  const searchParams = useSearchParams();
  const userId = searchParams.get('userId') || null;
  const {
    // Status
    language,
    direction,
    isLoading,
    loadingMessage,
    plan,
    hoveredIntro,
    selectedIndex,
    isNewUser,
    userLevel,
    showMainInterface,
    selectedPlanIndex,
    availablePlans,
    needsPlanSelection,
    // 状态更新函数
    setLanguage,
    setDirection,
    setHoveredIntro,
    setSelectedIndex,
    setPlan,
    setSelectedPlanIndex,
    // 方法
    fetchInitialData,
    handleGeneratePlan,
    handleConfirmSelection,
    handlePlanSelection,
    handleCreateNewTask,
    handleGoBackToPlanSelection,
    handleLevelUpdate, // <-- 确保解构了 handleLevelUpdate
  } = usePlan(userId); // <--- 将 userId 传递给 usePlan hook

  // 初始化数据加载
  React.useEffect(() => {
    // 确保 userId 存在后再加载数据
    if (userId) {
      fetchInitialData();
    } else {
      // 处理 userId 不存在的情况，例如重定向到登录页或显示错误
      console.error("ChoosePage: userId is missing, cannot fetch initial data.");
      // 你可能需要设置一个错误状态或导航到登录页面
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userId]); // 添加 userId 作为依赖项，以便在 userId 变化时重新加载

  return (
    <div className="flex items-center justify-center min-h-screen bg-gray-100 dark:bg-gray-900 relative">
      {/* 加载遮罩 */}
      {isLoading && <LoadingOverlay message={loadingMessage} />}

      {/* 条件渲染主要界面 */}
      {!isLoading && showMainInterface && userId && ( // 确保 userId 存在才渲染 MainInterface
        <MainInterface
          plan={plan}
          userLevel={userLevel}
          selectedPlanIndex={selectedPlanIndex}
          language={language}
          direction={direction}
          userId={userId} // 传递 userId 给 MainInterface
          isLoading={isLoading}
          onGoBack={handleGoBackToPlanSelection}
          onCreateNewTask={handleCreateNewTask}
          onPlanSelect={setSelectedPlanIndex}
          onLevelUpdate={handleLevelUpdate} // <-- 将 handleLevelUpdate 传递给 MainInterface
        />
      )}

      {/* 计划选择界面 */}
      {!isLoading && needsPlanSelection && (
        <PlanSelectionInterface
          availablePlans={availablePlans}
          onPlanSelect={(plan) => handlePlanSelection(plan)}
           //函数调用关系
        />
      )}

      {/* 欢迎/计划生成流程 */}
      {!isLoading && !showMainInterface && !needsPlanSelection && (
        <div className="w-full max-w-md">
          {/* 计划选择(新用户生成后) */}
          {plan && (
            <div className="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg">
              <h1 className="text-xl font-bold text-center mb-6 dark:text-white">学习计划</h1>
              <p className="text-sm text-gray-600 dark:text-gray-400 text-center mb-4">
                请选择符合您当前学习进度的计划点
              </p>
              {hoveredIntro && (
                <div className="mb-4 p-4 border border-gray-300 dark:border-gray-600 rounded-lg bg-gray-50 dark:bg-gray-700">
                  <p className="text-sm text-gray-700 dark:text-gray-300">{hoveredIntro}</p>
                </div>
              )}
              <div className="grid grid-cols-2 gap-4">
                {plan.plans.slice(0, 10).map((item: string, index: number) => (
                  <div
                    key={index}
                    className={`border border-gray-300 dark:border-gray-600 rounded-lg p-4 cursor-pointer transition-colors duration-150 ${
                      selectedIndex === index
                        ? "bg-indigo-600 text-white ring-2 ring-indigo-400"
                        : "text-gray-900 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700"
                    }`}
                    onClick={() => setSelectedIndex(index)}
                    onMouseEnter={() => setHoveredIntro(plan.intro[index])}
                  >
                    {item}
                  </div>
                ))}
              </div>
              <div className="flex justify-between mt-6">
                <button
                  onClick={() => { setPlan(null); setSelectedIndex(null); setHoveredIntro(""); }}
                  className="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded"
                >
                  返回
                </button>
                <button
                  onClick={handleConfirmSelection}
                  className={`font-bold py-2 px-4 rounded ${ selectedIndex === null ? "bg-gray-400 text-gray-700 cursor-not-allowed" : "bg-indigo-600 hover:bg-indigo-700 text-white" }`}
                  disabled={selectedIndex === null}
                >
                  确定
                </button>
              </div>
            </div>
          )}

          {/* 初始表单(新用户无计划时) */}
          {!plan && (
            <div className="bg-white dark:bg-gray-800 p-8 rounded-lg shadow-lg">
              <h1 className="text-xl font-bold text-center mb-6 dark:text-white">学习计划生成器</h1>
              <div className="mb-4">
                <label htmlFor="language" className="block text-sm font-medium text-gray-700 dark:text-gray-300">编程语言</label>
                <select
                  id="language"
                  value={language}
                  onChange={(e) => setLanguage(e.target.value)}
                  className="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-gray-700 dark:text-gray-300"
                >
                  <option value="">--选择语言--</option>
                  <option value="python">Python</option>
                </select>
              </div>
              <div className="mb-6">
                <label htmlFor="direction" className="block text-sm font-medium text-gray-700 dark:text-gray-300">学习方向</label>
                <input
                  type="text"
                  id="direction"
                  value={direction}
                  onChange={(e) => setDirection(e.target.value)}
                  placeholder="例如：数据结构 (可留空)"
                  className="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:bg-gray-700 dark:text-gray-300"
                />
              </div>
              <button
                onClick={handleGeneratePlan}
                className={`w-full font-bold py-2 px-4 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${ !language ? "bg-gray-400 text-gray-700 cursor-not-allowed" : "bg-indigo-600 hover:bg-indigo-700 text-white" }`}
                disabled={!language}
              >
                生成计划
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// Default export: the Page component wrapping the client content with Suspense
export default function ChoosePage() {
  return (
    <Suspense fallback={<div className="flex items-center justify-center min-h-screen">Loading...</div>}>
      <ChooseClientContent />
    </Suspense>
  );
}
